/**
 * @file warning_task.c
 * @brief 检测电机掉线，通过蜂鸣器鸣叫出来
 * @author CT Y
 * @version 1.0
 * @date 2023-04-29
 * 
 * @par 修改日志:
 * Date          Version Author  Description
 * 2023-04-29    1.0     CT Y    由DJI的程序做了移植
 */

#include "detect_task.h"
#include "warning_task.h"
#include "cmsis_os.h"
#include "main.h"
#include "bsp_buzzer.h"
#include "bsp_led.h"

#include "remote_control.h"

static void warn_error(uint8_t num);
// void buzzer_on(uint16_t psc, uint16_t pwm);
// void buzzer_off(void);
//接收原始数据，为18个字节，给了36个字节长度，防止DMA传输越界
extern volatile char NUC_ControlState;
extern volatile uint8_t handshake_flag;

const error_t *error_list_test_local;




/**
 * @brief 报警任务，包含蜂鸣器和LED状态的统一控制
 * @param  argument         My Param doc
 * @author CT Y
 * @date 2023-04-29
 */
void warning_task(void const * argument)
{
    
    static uint8_t error, last_error;
    static uint8_t error_num;
    error_list_test_local = get_error_list_point();

    while(1)
    {
        error = 0;

        //find error
        for(error_num = 0; error_num < REFEREE_TOE; error_num++)
        {
            if(error_list_test_local[error_num].error_exist)
            {
                error = 1;
                break;
            }
        }
        if(handshake_flag == 0){ //握手上了
            if(NUC_ControlState == 1){ //控制权在NUC
                LED_whiteON();
            }else{//控制权在遥控器
                LED_greenON();
            }

        }
        //no error, stop buzzer
        if(error == 0 && last_error != 0)
        {
            buzzer_off();
            if(handshake_flag == 1){
                LED_redOFF();//红灯熄灭，表示电机在线
            }
        }
        //have error
        if(error)
        {
            warn_error(error_num+1);
            if(handshake_flag == 1){
                LED_redON(); //红灯常亮，表示电机掉线
            }
        }
        



        last_error = error;
        osDelay(10);
    }
}



 


/**
 * @brief 蜂鸣器和红色灯进行报警，在握手成功后就不会再报警
 * @param  num              蜂鸣器鸣叫次数
 * @author CT Y
 * @date 2023-04-29
 */
static void warn_error(uint8_t num)
{
    static uint8_t show_num = 0;
    static uint8_t stop_num = 100;
    if(show_num == 0 && stop_num == 0)
    {
        show_num = num;
        stop_num = 100;
    }
    else if(show_num == 0)
    {
        stop_num--;
        buzzer_off();
    }
    else
    {
        static uint8_t tick = 0;
        tick++;
        if(tick < 50)
        {
            buzzer_off();
        }
        else if(tick < 100)
        {
            buzzer_on(1, 30000);
        }
        else
        {
            tick = 0;
            show_num--;
        }
    }
}




